import express from 'express';
import sql from '../../sql.js';
const router = express.Router();

// 查询分享资源接口
router.post('/searchShare', async (req, res) => {
  const keyword = req.body.keyword || null;
  const categoryId = req.body.categoryId || null;
  let page = parseInt(req.body.page) || 1;
  const pageSize = parseInt(req.body.pageSize) || 10;
  let shares;

  // 构建查询基础部分
  let query = 'SELECT s.*, s.download AS download_count ';
  query += 'FROM share s ';
  let whereClauses = [];
  let values = [];

  // 根据参数添加条件
  if (keyword) {
      whereClauses.push('s.title LIKE?');
      values.push(`%${keyword}%`);
  }
  if (categoryId) {
      whereClauses.push('s.category_id =?');
      values.push(categoryId);
  }

  if (whereClauses.length > 0) {
      query += ' WHERE ' + whereClauses.join(' AND ');
  }

  // 分页
  query += ' LIMIT ?,?';
  values.push((page - 1) * pageSize, pageSize);

  // 计算总数
  const countQuery = `SELECT COUNT(*) AS totalCount FROM share s ${whereClauses.length > 0? ' WHERE ' + whereClauses.join(' AND ') : ''}`;
  const [countResult] = await sql.query(countQuery, values);
  const totalCount = countResult[0].totalCount;
  const totalPages = Math.ceil(totalCount / pageSize);

  try {
      [shares] = await sql.query(query, values);
      if (shares.length === 0 && page > 1) {
        page = page - 1;
        values[values.length-2] = (page - 1) * pageSize;
        const [data] = await sql.query(query, values);
        shares = data;
      }

      res.send({
          status: 'success',
          message: '分享资源查询成功',
          data: shares,
          pagination: {
              currentPage: page,
              pageSize: pageSize,
              totalCount: totalCount,
              totalPages: totalPages
          }
      });
  } catch (error) {
      console.error('查询错误：', error);
      res.send({
          status: 'error',
          message: '服务器内部错误',
          errorCode: 500
      });
  }
});

// 增加分享资源接口
router.post('/addShare', async (req, res) => {
  let { title, category_id, path, password, image } = req.body;
  category_id = category_id || 1;
  try {
      // 检查标题是否已存在
      const checkQuery = 'SELECT * FROM share WHERE title =?';
      const [existingShares] = await sql.query(checkQuery, [title]);
      if (existingShares.length > 0) {
          return res.send({
              status: 'error',
              message: '标题已存在',
              errorCode: 400
          });
      }

      const query = 'INSERT INTO share (title, category_id, path, password, image) VALUES (?,?,?,?,?)';
      const values = [title, category_id, path, password, image];
      await sql.query(query, values);
      res.send({
          status: 'success',
          message: '分享资源添加成功'
      });
  } catch (error) {
      console.error('添加分享资源错误：', error);
      res.send({
          status: 'error',
          message: '服务器内部错误',
          errorCode: 500
      });
  }
});

// 编辑分享资源接口
router.put('/updateShare/:shareId', async (req, res) => {
  const shareId = req.params.shareId;
  let { title, category_id, path, password, image } = req.body;
  try {
      // 检查新标题是否已存在（排除当前正在编辑的资源）
      const checkQuery = 'SELECT * FROM share WHERE title =? AND ID!=?';
      const [existingShares] = await sql.query(checkQuery, [title, shareId]);
      if (existingShares.length > 0) {
          return res.send({
              status: 'error',
              message: '标题已存在',
              errorCode: 409
          });
      }

      let updateQuery = 'UPDATE article SET ';
      const values = [];
      if (title) {
        updateQuery += 'title =?, ';
        values.push(title);
      }
      if (category_id) {
        updateQuery += 'category_id =?, ';
        values.push(category_id);
      }
      if (path) {
        updateQuery += 'path =?, ';
        values.push(path);
      }
      if (password) {
        updateQuery += 'password =?, ';
        values.push(password);
      }
      if (image) {
        updateQuery += 'image =?, ';
        values.push(image);
      }
      // 去除末尾的逗号和空格
      updateQuery = updateQuery.slice(0, -2);
      updateQuery += ' WHERE ID =?';
      values.push(shareId);
      await sql.query(updateQuery, values);
      res.send({
          status: 'success',
          message: '分享资源编辑成功'
      });
  } catch (error) {
      console.error('编辑分享资源错误：', error);
      res.send({
          status: 'error',
          message: '服务器内部错误',
          errorCode: 500
      });
  }
});

// 删除分享资源接口
router.delete('/deleteShare/:shareId', async (req, res) => {
  const shareId = req.params.shareId;
  try {
      const query = 'DELETE FROM share WHERE ID =?';
      await sql.query(query, [shareId]);
      res.send({
          status: 'success',
          message: '分享资源删除成功'
      });
  } catch (error) {
      console.error('删除分享资源错误：', error);
      res.send({
          status: 'error',
          message: '服务器内部错误',
          errorCode: 500
      });
  }
});

export default router;
